package com.typhoon.client;

import com.typhoon.cache.CacheManager;
import com.typhoon.dto.UserDto;
import com.typhoon.service.UserService;
import org.springframework.beans.factory.InitializingBean;

/**
 * 用户信息操作客户端
 *
 * @author Typhoon
 * @date 2018-05-20 16:04 Sunday
 * @since V2.0.0
 */
public class UserReadClient implements InitializingBean {

    private static final String KEY_PREFIX = "userCachePrefix:";

    private CacheManager cacheManager;

    private UserService userService;

    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 查询用户信息
     *
     * @param id
     * @return
     */
    public UserDto queryByPK(Long id) {
        if(null == id || id <= 0) {
            throw new IllegalArgumentException("参数非法");
        }
        UserDto userDto = this.cacheManager.get(KEY_PREFIX + id,UserDto.class);
        if(null != userDto) {//走缓存
            return userDto;
        }
        //走DB
        userDto = this.userService.queryByPK(id);
        try {
            this.cacheManager.put(KEY_PREFIX + id,userDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userDto;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(null == cacheManager || null == userService) {
            throw new IllegalArgumentException("tCache 或者userService没有初始化 ");
        }
    }
}
